<?php
namespace app\attachment\controller;

use app\common\controller\Front;

class Index extends Front
{
    public function _initialize()
    {
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        
        parent::_initialize();
    }
    
    //首页
    public function index()
    {
        return $this->fetch();
    }
    
    //按ID查询
    public function id()
    {
        //ID参数
        if(!$val = input('val/d',0)){
            $this->error(lang('mustIn'));
        }
        //查询数据
        $info = model('common/Info','loglic')->get([
            'cache'  => true,
            'status' => 'normal',
            'module' => 'attachment',
            'with'   => 'info_meta',
            'id'     => $val,
        ]);
        //公共入口
        $this->detail($info);
    }
    
    //按slug查询
    public function slug()
    {
        //ID参数
        if(!$val = input('val/s')){
            $this->error(lang('mustIn'));
        }
        //查询数据
        $info = model('common/Info','loglic')->get([
            'cache'  => true,
            'status' => 'normal',
            'module' => 'attachment',
            'with'   => 'info_meta',
            'slug'   => $val,
        ]);
        //公共入口
        $this->detail($info);
    }
    
    //按path查询
    public function path()
    {
        //ID参数
        if(!$val = input('val/s')){
            $this->error(lang('mustIn'));
        }
        //查询数据
        $info = model('common/Info','loglic')->get([
            'cache'   => true,
            'status'  => 'normal',
            'module'  => 'attachment',
            'with'    => 'info_meta',
            'excerpt' => $val,
        ]);
        //公共入口
        $this->detail($info);
    }
    
    //公用detail
    private function detail($info=[])
    {
        if(!$info){
            $this->error(lang('empty'));
        }
        if(!$info['info_mime_type']){
            $this->error(lang('attachment/error/mimeType'));
        }
        //本地附件与网络文件
        if(attachmentIsHost($info['info_excerpt'])){
            if(substr($info['info_mime_type'],0,5) == 'image'){
                $this->hostImage($info);
            }else{
                $this->hostFile($info);
            }
        }else{
            $this->outer($info);
        }
    }
    
    //本地图片
    private function hostImage($info=[])
    {
        //是否禁用
        if(!config('attachment.open_image')){
            $this->error(lang('open_option_close'));
        }
        //图片水印
        if(config('common.upload_water_locate')){
            $fileArray = pathinfo($info['info_excerpt']);
            $filePath = $fileArray['dirname'].'/'.$fileArray['filename'].'_water.'.$fileArray['extension'];
        }else{
            $filePath = $info['info_excerpt'];
        }
        //发送到浏览器
        if(config('attachment.open_image') == 2){
            if($result = attachmentSendBrowser($filePath, $info['info_title'], $info['info_mime_type'])){
                exit($result);
            }else{
                exit($this->browserError());
            }
        }
        //跳转真实地址
        $filePath = $this->site['path_root'].trim(config('common.upload_path')).'/'.$filePath;
        if(config('common.upload_cdn')){
            $this->redirect(rtrim(config('common.upload_cdn'),'/').$filePath, 302);
        }else{
            $this->redirect($filePath, 302);
        }
    }
    
    //本地文件
    private function hostFile($info=[])
    {
        //是否禁用
        if(!config('attachment.open_file')){
            $this->error(lang('open_option_close'));
        }
        //附件积分处理
        $this->scoreCheck($info['info_id'], $info['attachment_score'], $info['info_user_id']);
        //发送到浏览器
        if(config('attachment.open_file') == 2){
            if($result=attachmentSendBrowser($info['info_excerpt'], $info['info_title'], $info['info_mime_type'])){
                exit($result);
            }else{
                $this->browserError();
            }
        }
        //跳转真实地址
        $jumpUrl = $this->site['path_root'].trim(config('common.upload_path')).'/'.$info['info_excerpt'];
        if(config('common.upload_cdn')){
            $this->redirect(rtrim(config('common.upload_cdn'),'/').$jumpUrl, 302);
        }else{
            $this->redirect($jumpUrl, 302);
        }
    }
    
    //网络文件
    private function outer($info=[])
    {
        //是否禁用
        if(!config('attachment.open_outer')){
            $this->error(lang('open_option_close'));
        }
        //附件积分处理
        $this->scoreCheck($info['info_id'], $info['attachment_score'], $info['info_user_id']);
        //发送到浏览器
        if(config('attachment.open_outer') == 2){
            if($result=attachmentCurlBrowser($info['info_excerpt'], $info['info_title'], $info['info_mime_type'])){
                exit($result);
            }else{
                exit($this->browserError());
            }
        }
        //跳转真实地址
        $this->redirect($info['info_excerpt'], 302);
    }
    
    //浏览器输出错误
    private function browserError()
    {
        header('Content-Type: image/png');
        header('Content-Length: 821');
        return readfile('./public/images/water.png');
        //header('Content-Type: text/plain');
        //exit(lang(config('daicuo.error')));
    }
    
    /**
     * 附件积分处理
     * @param int $infoId 附件ID
     * @param int $infoScore 所需积分
     * @param int $infoUserId 附件上传用户
     * @return obj 文件流
     */
    private function scoreCheck($infoId=0, $infoScore=0, $infoUserId=0)
    {
        //积分处理开关
        if($infoScore < 1){
            return true;
        }
        //未安装USER插件
        if(!function_exists('userScoreDec')){
            $this->error(lang('attachment/error/system'));
        }
        //判断用户是否登录
        if( !$this->site['user']['user_id'] ){
            $this->error(lang('attachment/error/needLogin'), 'user/login/index');
        }
        //当前用户自己上传的附件
        if( $this->site['user']['user_id'] == $infoUserId){
            return true;
        }
        //是否已经购买过了
        if( attachmentGetScore($this->site['user']['user_id'], $infoId) ){
            return true;
        }
        //用户积分是否足够扣除本次请求
        if($infoScore > $this->site['user']['user_score']){
            $this->error(lang('attachment/error/scoreLess'), 'user/recharge/index');
        }
        //根据扣点设置扣除用户的积分
        if(!userScoreDec($this->site['user']['user_id'], $infoScore)){
            $this->error(lang('attachment/error/system'));
        }
        //增加积分消费记录
        attachmentSetScore($this->site['user']['user_id'], $infoId, $infoScore*-1);
    }
}